package cn.demomaster.quickui_sample.ui.fragment.main;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.demomaster.quickcompat.view.adapter.ScrollingTabsAdapter;
import com.demomaster.quickcompat.view.menu.NavMenuItem;
import com.demomaster.quickcompat.view.menu.OptionsMenu;
import com.demomaster.quickcompat.widget.layout.AutoCenterHorizontalScrollView;
import com.demomaster.quickcompat.widget.layout.QuickScrollableTabView;
import com.demomaster.quickcompat.widget.base.QuickGravity;
import com.demomaster.quickcompat.widget.dialog.QuickActionDialog;
import com.demomaster.quickcompat.widget.dialog.QuickDialog;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import cn.demomaster.quicklogger.QdLog;
import cn.demomaster.quickpicturer.helper.PhotoHelper;
import cn.demomaster.quickrouter.fragment.QuickFragment;
import com.demomaster.quickcompat.widget.toast.QdToast;
import cn.demomaster.quickui.operatguid.GuiderView;
import cn.demomaster.quickui_sample.R;
import cn.demomaster.quickui_sample.ui.fragment.component.BlankFragment;
import cn.demomaster.quickui.ui.fragment.WebViewFragment;
import cn.demomaster.quickui.util.ClipboardUtil;

/**
 * Squirrel桓
 * 2018/8/25
 */
public class MainFragment extends QuickFragment {

    @Nullable
    @Override
    public View onGenerateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_layout_main, null);
        return view;
    }

    /* @Override
     public void initView(View rootView, ActionBarLayout2 actionBarLayout) {
         *//*actionBarLayout.setActionBarModel(ActionBarLayout2.ACTIONBAR_TYPE.NORMAL);
        actionBarLayout.getLeftView().setVisibility(View.GONE);

        List<Class> list = new ArrayList<>();
        list.add(ComponentFragment.class);
        list.add(HelperFragment.class);
        list.add(DesignPatternFragment.class);
        MainFragmentAdapter mPagerAdapter1 = new MainFragmentAdapter(getActivity().getSupportFragmentManager(), list);
        // Initiate ViewPager
        ViewPager mViewPager = rootView.findViewById(R.id.viewPager);
        //mViewPager.setPageMargin(getResources().getInteger(R.integer.viewpager_margin_width));
        //mViewPager.setPageMarginDrawable(R.drawable.viewpager_margin);
        mViewPager.setOffscreenPageLimit(1);
        mViewPager.setAdapter(mPagerAdapter1);
        mViewPager.setCurrentItem(0);

        // Tabs
        initScrollableTabs(rootView, mViewPager);
        init();*//*
    }*/

    public void initView(View rootView) {
        /*FloatViewImp floatView = new FloatViewImp() {
            @Override
            public View onCreateView(Bundle savedInstanceState) {
                ImageView imageView = new ImageView(mContext);
                imageView.setImageResource(R.mipmap.dk_doraemon);
                return imageView;
            }
        };
        FloatHelper.getInstance().showFloatView(mContext,floatView);*/

       /* actionBarLayout.setFullScreen(true);
        actionBarLayout.setActionBarType(ACTIONBAR_TYPE.NORMAL);
        actionBarLayout.setHeaderBackgroundColor(getResources().getColor(R.color.colorPrimary));
        actionBarLayout.getLeftView().setVisibility(View.GONE);*/
        List<Class> list = new ArrayList<>();
        list.add(ComponentFragment.class);
        list.add(HelperFragment.class);
        list.add(DesignPatternFragment.class);
        FragmentManager fragmentManager = getChildFragmentManager();
        MainFragmentAdapter mPagerAdapter1 = new MainFragmentAdapter(getActivity(), list);
        // Initiate ViewPager
        ViewPager2 mViewPager = rootView.findViewById(R.id.viewPager);
        //mViewPager.setPageMargin(getResources().getInteger(R.integer.viewpager_margin_width));
        //mViewPager.setPageMarginDrawable(R.drawable.viewpager_margin);
        mViewPager.setOffscreenPageLimit(1);
        mViewPager.setAdapter(mPagerAdapter1);
        mViewPager.setCurrentItem(0);

        // Tabs
        initScrollableTabs(rootView, mViewPager);
        /*ImageView iv_store_pic = rootView.findViewById(R.id.iv_store_pic);
        Glide.with(mContext).load("https://baekteoriappimg.s3.ap-northeast-2.amazonaws.com/charge/158633285847768584298").into(iv_store_pic);
        iv_store_pic.setVisibility(View.VISIBLE);*/
        getActionBarTool().setTitle(getString(cn.demomaster.quickui.R.string.title_home));
        //getActionBarTool().setStateBarColorAuto(true);//状态栏文字颜色自动
        //getActionBarTool().setActionBarThemeColors(Color.WHITE, Color.BLACK);
        getActionBarTool().setLeftOnClickListener(view -> {
            /*LoadingDialog.Builder builder = new LoadingDialog.Builder(MainActivity.this);
            final LoadingDialog loadingDialog = builder.setMessage("登陆中").setCanTouch(false).create();
            loadingDialog.show();*/
            QuickActionDialog.Builder builder = new QuickActionDialog.Builder(mContext).setContentViewLayout(cn.demomaster.quickui.R.layout.quick_dialog_loading_default);
            final QuickActionDialog customDialog = builder.setCancelable(false).create();
            customDialog.show();
        });
        getActionBarTool().getLeftView().setVisibility(View.GONE);
        getActionBarTool().setRightOnClickListener(v -> optionsMenu.show(v));
    }

    OptionsMenu optionsMenu;
    private OptionsMenu.Builder optionsMenubuilder;

    @Override
    public int getMenuRes() {
        return R.menu.activity_main_drawer;
    }

    @Override
    public void initOptionsMenu(Menu navMenu) {
        List<NavMenuItem> menus = new ArrayList<>();
        for (int i = 0; i < navMenu.size(); i++) {
            NavMenuItem menu1 = new NavMenuItem(navMenu.getItem(i));
            menu1.setIconPadding(30);
            menu1.setIconWidth(80);
            menus.add(menu1);
        }
        optionsMenubuilder = new OptionsMenu.Builder(mContext);
        optionsMenubuilder.setMenus(menus)
                .setAlpha(.6f)
                .setBackgroundRadius(20)
                .setWithArrow(true)
                .setArrowHeight(30)
                .setArrowWidth(30)
                .setGravity(QuickGravity.BOTTOM)
                .setDividerColor(getResources().getColor(R.color.transparent))
                .setAnchor(getActionBarTool().getRightView());

        optionsMenu = optionsMenubuilder.creat();
        optionsMenu.setOnMenuItemClicked(new OptionsMenu.OnMenuItemClicked() {
            @Override
            public void onItemClick(NavMenuItem menu, int position, View view) {
                onOptionsItemSelected(menu.getMenuItem());
            }
        });
        optionsMenu.setMenus(menus);
        optionsMenu.setAnchor(getActionBarTool().getRightView());
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if(item.getItemId()==R.id.nav_scan){
//            getPhotoHelper().scanQrcode(new PhotoHelper.OnTakePhotoResult() {
//                @Override
//                public void onSuccess(Intent data, String path) {
//                    //QdToast.show(mContext, path + "");
//                    showScanDialog(path);
//                }
//
//                @Override
//                public void onFailure(String error) {
//                    QdToast.show(mContext, "error:" + error);
//                }
//            });
            optionsMenu.dismiss();
                   /* photoHelper.selectPhotoFromGalleryAndCrop(new PhotoHelper.OnTakePhotoResult() {
                        @Override
                        public void onSuccess(Intent data, String path) {
                            *//*setImageToView(data);*//*
                        }

                        @Override
                        public void onFailure(String error) {

                        }
                    });*/
        }else if(item.getItemId()==R.id.nav_screenshot){
            //ScreenShotUitl.shot((Activity) mContext);
            optionsMenu.dismiss();
        }
        return super.onOptionsItemSelected(item);
    }

    //    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.main, menu);
//        return true;
//    }

    private void showScanDialog(String url) {
        QuickDialog quickDialog = new QuickDialog.Builder(mContext)
                .create();
        quickDialog.bindView(R.id.tv_title, "要跳转到指定页面吗？")
                .bindView(R.id.tv_message, "" + url)
                .bindView(R.id.tv_left, "复制", (dialog, view, tag) -> {
                    ClipboardUtil.setClip(getContext(), "" + url);
                    QdToast.show("copy success");
                    dialog.dismiss();
                })
                .bindView(R.id.tv_right, "跳转", (dialog, view, tag) -> {
                    dialog.dismiss();
                    WebViewFragment webViewFragment = new WebViewFragment();
                    Bundle bundle = new Bundle();
                    bundle.putString("URL", url);
                    webViewFragment.setArguments(bundle);
                    Intent intent = new Intent();
                    intent.putExtras(bundle);
                    startFragment(webViewFragment, R.id.container1, intent);
                });
        quickDialog.show();
    }

    /**
     * Initiate the tabs
     */
    public void initScrollableTabs(View rootView, ViewPager2 mViewPager) {
        QuickScrollableTabView mScrollingTabs = rootView.findViewById(R.id.scrollingTabs);
        ScrollingTabsAdapter mScrollingTabsAdapter = new ScrollingTabsAdapter(getActivity(), cn.demomaster.quickui.R.layout.tabs);
        final String[] mTitles = getContext().getResources().getStringArray(R.array.tab_themt_titles);
        mScrollingTabsAdapter.setTitles(mTitles);
        mScrollingTabs.setTabsAdapter(mScrollingTabsAdapter);
        mScrollingTabs.setViewPager(mViewPager);
    }

    private static class MainFragmentAdapter extends FragmentStateAdapter {
        private List<Class> data;

        public MainFragmentAdapter(@NonNull @NotNull FragmentActivity fragmentActivity, List<Class> data) {
            super(fragmentActivity);
            this.data = data;
        }

        @NonNull
        @NotNull
        @Override
        public Fragment createFragment(int position) {
            Fragment fragment;
            Bundle bundle = new Bundle();
            String className = "";
            Class catClass = data.get(position);
            try {
                // catClass = Class.forName(className);
                // 实例化这个类
                fragment = (Fragment) catClass.newInstance();
                fragment.setArguments(bundle);
                return fragment;
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (java.lang.InstantiationException e) {
                e.printStackTrace();
            }

            fragment = new BlankFragment();
            fragment.setArguments(bundle);
            return fragment;
        }

        @Override
        public int getItemCount() {
            return data.size();
        }
    }


    //记录用户首次点击返回键的时间
    private long firstClickTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        QdLog.i("main onKeyDown " + isRootFragment());
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isRootFragment()) {
                if (System.currentTimeMillis() - firstClickTime > 2000) {
                    QdToast.show(mContext, "再点击退出app");
                    firstClickTime = System.currentTimeMillis();
                } else {
                    getActivity().finish();
                }
                return true;
            }
        }
        //QdToast.show(mContext, "onKeyDown isRootFragment=" + isRootFragment());
        return super.onKeyDown(keyCode, event);
    }
}